package jrdcom.com.onecodesample.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.DropBoxManager;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import jrdcom.com.onecodesample.DB.CoolWearherDB;
import jrdcom.com.onecodesample.Model.CityModel;
import jrdcom.com.onecodesample.Model.CountryModel;
import jrdcom.com.onecodesample.Model.ProvinceModel;
import jrdcom.com.onecodesample.Model.WeatherInfoModel;
import jrdcom.com.onecodesample.R;
import jrdcom.com.onecodesample.Util.HandleUtil;
import jrdcom.com.onecodesample.Util.HttpUtil;
import jrdcom.com.onecodesample.View.CustomTitleBar;

/**
 * Created by longcheng on 17/1/17.
 */
public class MainPageActivity extends AppCompatActivity implements CustomTitleBar.TitleBarClickListeter{
    private static final String TAG = "MainPageActivity";
    private List<String> dataList = new ArrayList<String>();
    private List<ProvinceModel> provinceModels = new ArrayList<ProvinceModel>();
    private List<CityModel> cityModels = new ArrayList<CityModel>();
    private List<CountryModel> countryModels = new ArrayList<CountryModel>();
    private CoolWearherDB coolWearherDB;
    private ArrayAdapter adapter;
    private int EntryType = 0; //0 province, 1 city, 2 country
    private ProvinceModel selectProvinceId;
    private CityModel selectCityId;
    private ProgressDialog vProgressDialog;
    private CustomTitleBar customTitleBar;
    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        Log.d("zlwu", "onCreate");
        super.onCreate(savedInstanceState, persistentState);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //check the weather code is ok
        WeatherInfoModel weatherInfoModel = new WeatherInfoModel();
        weatherInfoModel = HandleUtil.getLocalInfo(this);
        if(0 != weatherInfoModel.getWeatherCode()){
            Intent intent = new Intent(this, WeatherInfoActivity.class);
            startActivity(intent);
            return;
        }
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_main);
        //
        ListView listView = (ListView)findViewById(R.id.listview);
        customTitleBar = (CustomTitleBar)findViewById(R.id.customTitle);
        customTitleBar.setBtnClickListeter(this);
        /*customTitleBar.setLeftBtnHide(true);
        customTitleBar.setRightBtnHide(true);*/
        CustomTitleShow(true, true,"Province");

        EntryType = 0;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //get positions
                switch (EntryType){
                    case 0:
                        //Enter city list
                        CustomTitleShow(true, false, "City List");
                        //获取当前province的code
                        ProvinceModel provinceModel = provinceModels.get(position);
                        selectProvinceId = provinceModel;
                        getCityData(provinceModel.getProvinceCode(),selectProvinceId.getProvinceId());
                        break;
                    case 1:
                        //Entry Country list
                        CustomTitleShow(true, false, "Country List");
                        //获取当前City的code
                        CityModel cityModel = cityModels.get(position);
                        selectCityId = cityModel;
                        getCountryData(cityModel.getCityCode(),selectCityId.getCityId());
                        break;
                    case 2:
                        CountryModel countryModel = countryModels.get(position);
                        Intent intent = new Intent(MainPageActivity.this, WeatherInfoActivity.class);
                        intent.putExtra("country_name", countryModel.getCountryName());
                        intent.putExtra("country_code", countryModel.getCountryCode());
                        startActivity(intent);
                        break;
                }
                adapter.notifyDataSetChanged();
            }
        });
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        //get province data
        coolWearherDB = CoolWearherDB.getInstance(this);

        //获取getProvinceData
        getProvinceData();
    }

    @Override
    protected void onStart() {
        Log.d("zlwu", "onStart");
        super.onStart();
    }

    private void CustomTitleShow(Boolean leftShow, Boolean rightShow, String Title){
        customTitleBar.setLeftBtnHide(leftShow);
        customTitleBar.setRightBtnHide(rightShow);
        customTitleBar.setTitle(Title);
    }

    private void getProvinceData(){
        dataList.clear();

        customTitleBar.setTitle("Province");
        EntryType = 0;
        provinceModels = coolWearherDB.getProvinceList();
        if(null != provinceModels&& 0!= provinceModels.size()){
            for(ProvinceModel provinceModel:provinceModels){
                String provinceName = provinceModel.getProvinceName();
                dataList.add(provinceName);
            }
        }else{
            getDataFromServer("Province", null, 0);
        }
    }

    private void getCityData(String code,int province_id){
        dataList.clear();

        EntryType = 1;
        cityModels = coolWearherDB.getCityList(province_id);
        if(null != cityModels && 0!=cityModels.size()){
            for(CityModel cityModel :cityModels){
                String cityName = cityModel.getCityName();
                dataList.add(cityName);
            }
        }else{
            getDataFromServer("City", code, province_id);
        }
    }

    private void getCountryData(String code, int city_id){
        dataList.clear();

        EntryType = 2;
        countryModels = coolWearherDB.getCountryList(city_id);
        if(null != countryModels && 0!= countryModels.size()){
            for(CountryModel countryModel : countryModels){
                String countryName = countryModel.getCountryName();
                dataList.add(countryName);
            }
        }else{
            getDataFromServer("Country", code, city_id);
        }
    }


    private void getDataFromServer(final String type,final String code, final int parentId){
        String address = null;
        switch (type){
            case  "Province":
                address = "http://www.weather.com.cn/data/list3/city.xml";
                break;
            case "City":
            case "Country":
                address = "http://www.weather.com.cn/data/list3/city" + code +".xml";
                break;

        }
        showProgressDialog();
        HttpUtil.sendHttpRequest(address, new HttpUtil.HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                Log.d("zlwu", "sendHttpRequest OK");
                boolean result = false;
                switch (type){
                    case "Province":
                        result =  HandleUtil.handleProvinceResponse(coolWearherDB, response);
                        getProvinceData();
                        break;
                    case "City":
                        result = HandleUtil.handleCityResponse(coolWearherDB, response, parentId);
                        getCityData(code, parentId);
                        break;
                    case "Country":
                        result = HandleUtil.handleCountryResponse(coolWearherDB, response, parentId);
                        getCountryData(code, parentId);
                        break;

                }
                if(true == result){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            adapter.notifyDataSetChanged();
                        }
                    });
                }

            }

            @Override
            public void onError(Exception e) {

            }
        });

    }

    private void getProvinceFromServer(){
        String provinceAddress = "http://www.weather.com.cn/data/list3/city.xml";
        //"http://www.weather.com.cn/data/list3/city" + code +".xml"
        HttpUtil.sendHttpRequest(provinceAddress, new HttpUtil.HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                //parse
                HandleUtil.handleProvinceResponse(coolWearherDB, response);
                getProvinceData();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        if(2 == EntryType){
            //go to city list
            CustomTitleShow(true, false, "City List");
            getCityData(selectProvinceId.getProvinceCode(), selectProvinceId.getProvinceId());
            adapter.notifyDataSetChanged();
        }else if(1 == EntryType){
            //go to province list
            CustomTitleShow(false, false, "City List");
            getProvinceData();
            adapter.notifyDataSetChanged();
        }else{
            //退出
            //super.onBackPressed();
            this.finish();
        }
    }

    private void showProgressDialog(){
        Log.d("zlwu","showProgressDialog");
        if(null == vProgressDialog){
            vProgressDialog = new ProgressDialog(this);
            vProgressDialog.setMessage("Loading");
            vProgressDialog.setCanceledOnTouchOutside(true);
        }
        vProgressDialog.show();

    }

    private void closeProgressDialog(){
        Log.d("zlwu", "closeProgressDialog");
        if(null != vProgressDialog){
            vProgressDialog.dismiss();
        }
    }
    //TitleBarClick listener

    @Override
    public void LeftBtnClick() {
        onBackPressed();
    }

    public  void RightBtnClick(){
        //do nothing
    }

    @Override
    public void TitleClick() {

    }
}
